import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
let bookList = window.sessionStorage.getItem('bookList')
let cartList = window.sessionStorage.getItem('cartList')
let itemList = window.sessionStorage.getItem('itemList')
let store =  new Vuex.Store({
  state: {
    bookList: bookList? JSON.parse(bookList):[],
    cartList: cartList? JSON.parse(cartList):[],
    itemList: itemList? JSON.parse(itemList):[],
  },
  getters: {
  },
  mutations: {
    setBookList(state, data) {
      state.bookList = data;
    },
    // 加入书架
    addToCart(state,data) {
      // data.isAdd = true  他不行
      // 关闭开关 告诉用户已经在书架了
      Vue.set(data, 'isAdd', true)
      // 深拷贝数据改变引用地址  防止元数据被修改导致bug
      let newData = JSON.parse(JSON.stringify(data))
      newData.checked = false;
      state.cartList.push(newData)
    },
    // 删除cartList里面book
    delCL(state,id) {
      state.cartList.forEach((v,i) => {
        if(v.id === id) {
          state.cartList.splice(i,1)
        }
      })
    },
    // 删除itemList里面book
    delItemListBook(state,data) {
      state.itemList.forEach((v,i) => {
        if(data.itemId === v.itemId) { // 找到分组
          v.list.forEach((vv,ii) => {
            if(vv.id === data.bookId) {
              state.itemList[i].list.splice(ii,1)
              if(state.itemList[i].list.length === 0) {
                store.commit('delItem', data.itemId)
              }
            }
          })
        }
      })
    },
    createItemList(state, data) {
      state.itemList.push(data)
    },
    // 编辑分组名称
    editItemName(state,data) {
      state.itemList.forEach((v,i) => {
        if(v.itemId === data.id) {
          v.name = data.name;
        }
      })
    },
    // 删除分组
    delItem(state, id) {
      state.itemList.forEach((v,i) => {
        if(v.itemId === id) {
          state.itemList.splice(i,1)
        }
      })
    }
  },
  actions: {
  },
  modules: {
  }
})
store.subscribe((mutations, state) => {
  if(state.bookList) {
    window.sessionStorage.setItem('bookList', JSON.stringify(state.bookList))
  }
  if(state.cartList) {
    window.sessionStorage.setItem('cartList', JSON.stringify(state.cartList))
  }
  if(state.itemList) {
    window.sessionStorage.setItem('itemList', JSON.stringify(state.itemList))
  }
})
export default store;
